package com.geniusk.wss;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Slf4j
@Configuration
public class WsServer {

    @Value("${iot.wss.port}")
    private Integer port;

    private static class SingleWSServer{
        static final WsServer instance = new WsServer();
    }

    public static WsServer getInstance(){
        return SingleWSServer.instance;
    }

    private final ServerBootstrap server;

    public WsServer(){
        EventLoopGroup mainGroup = new NioEventLoopGroup();
        EventLoopGroup subGroup = new NioEventLoopGroup();
        server = new ServerBootstrap();
        server.group(mainGroup, subGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_RCVBUF, 1024 * 16) // 设置接收缓冲区为16KB
                .childHandler(new WsChannelInitializer());
    }

    public void start() {
        server.bind(port);
        log.info("netty websocket server start, port: {}", port);
    }
}